/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Usuarios;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author Smuggler
 */
public class ConfigServer extends javax.swing.JFrame {
 private Properties prop;
    private InputStream is;
    private OutputStream os;
    JFileChooser chooser;
    String txtNombre = "";
    public static String rutaPropertiesFile = "Configuraciones.properties";
    private Usuarios usuario;
    private static JFrame frame;

    public JFrame getFrame() {
        return frame;
    }

    /**
     * Creates new form ConfigServer
     */
    public ConfigServer(Usuarios usuario) {
        initComponents();
        cargarDatos();
        this.usuario = usuario;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        hostLabel = new javax.swing.JLabel();
        hostField = new javax.swing.JTextField();
        puertoLabel = new javax.swing.JLabel();
        puertoField = new javax.swing.JTextField();
        usuarioLabel = new javax.swing.JLabel();
        usuarioField = new javax.swing.JTextField();
        passwordLabel = new javax.swing.JLabel();
        passwordField = new javax.swing.JTextField();
        dbLabel = new javax.swing.JLabel();
        dbField = new javax.swing.JTextField();
        guardarButton = new javax.swing.JButton();

        hostLabel.setText("Host:");

        puertoLabel.setText("Puerto:");

        usuarioLabel.setText("Usuario:");

        passwordLabel.setText("Password:");

        passwordField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                passwordFieldActionPerformed(evt);
            }
        });

        dbLabel.setText("Base de Datos:");

        dbField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                dbFieldActionPerformed(evt);
            }
        });

        guardarButton.setText("Guardar");
        guardarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(puertoLabel)
                            .addComponent(hostLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(puertoField, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE)
                            .addComponent(hostField)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(usuarioLabel)
                            .addComponent(passwordLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(usuarioField, javax.swing.GroupLayout.DEFAULT_SIZE, 293, Short.MAX_VALUE)
                            .addComponent(passwordField)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(guardarButton)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(dbLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 60, Short.MAX_VALUE)
                        .addComponent(dbField, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hostLabel)
                    .addComponent(hostField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(puertoLabel)
                    .addComponent(puertoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usuarioLabel)
                    .addComponent(usuarioField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordLabel)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dbLabel)
                    .addComponent(dbField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(26, 26, 26)
                .addComponent(guardarButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
     public boolean propertiesFileGenerado() {
        FileInputStream is = null;
        try {
            is = new FileInputStream(rutaPropertiesFile);
            is.close();
            return true;
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "No se puede abrir el archivo properties/No está creado");
            return false;
        }
    }

    private void cargarDatos(){
        
        FileInputStream is;
        Properties prop = new Properties();
        if (propertiesFileGenerado()) {
            try {
                is = new FileInputStream(ConfigServer.rutaPropertiesFile);
                prop.load(is);
                is.close();
            } catch (IOException ioex) {
                ioex.printStackTrace();
            }
            hostField.setText(prop.getProperty("host"));
            puertoField.setText( prop.getProperty("puerto"));
            usuarioField.setText(prop.getProperty("usuario"));
            passwordField.setText(prop.getProperty("pass"));
            dbField.setText(prop.getProperty("db"));
        }

    
    }
    
    private void dbFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_dbFieldActionPerformed

    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
    configServerToggleButtonActionPerformed();
    }//GEN-LAST:event_guardarButtonActionPerformed

    private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_passwordFieldActionPerformed
 private void configServerToggleButtonActionPerformed() {                                                         


        prop = new Properties();
        is = null;
        os = null;
        

        try {
            is = new FileInputStream(rutaPropertiesFile);
        } catch (IOException e) {
            System.out.println(e.toString());
        }
        try {
            prop.load(is);
            is.close();
            Properties newProps = new Properties();
            Enumeration enumProps = prop.propertyNames();
            String key = "";
            if (!enumProps.hasMoreElements()) {
                newProps.setProperty("host", hostField.getText());
            }
            while (enumProps.hasMoreElements()) {
                key = (String) enumProps.nextElement();
                if (key.equals("host")) {
                    newProps.setProperty("host",  hostField.getText());
                } else {
                    newProps.setProperty(key, prop.getProperty(key));
                    if (!enumProps.hasMoreElements()) {
                        newProps.setProperty("host",  hostField.getText());
                    }
                }
            }
           
            key = "";
            if (!enumProps.hasMoreElements()) {
                newProps.setProperty("puerto", puertoField.getText());
            }
            while (enumProps.hasMoreElements()) {
                key = (String) enumProps.nextElement();
                if (key.equals("puerto")) {
                    newProps.setProperty("puerto",  puertoField.getText());
                } else {
                    newProps.setProperty(key, prop.getProperty(key));
                    if (!enumProps.hasMoreElements()) {
                        newProps.setProperty("puerto",  puertoField.getText());
                    }
                }
            }
            
            key = "";
            if (!enumProps.hasMoreElements()) {
                newProps.setProperty("usuario", usuarioField.getText());
            }
            while (enumProps.hasMoreElements()) {
                key = (String) enumProps.nextElement();
                if (key.equals("usuario")) {
                    newProps.setProperty("usuario", usuarioField.getText());
                } else {
                    newProps.setProperty(key, prop.getProperty(key));
                    if (!enumProps.hasMoreElements()) {
                        newProps.setProperty("usuario",  usuarioField.getText());
                    }
                }
            }
            
            key = "";
            if (!enumProps.hasMoreElements()) {
                newProps.setProperty("pass", passwordField.getText());
            }
            while (enumProps.hasMoreElements()) {
                key = (String) enumProps.nextElement();
                if (key.equals("pass")) {
                    newProps.setProperty("pass",  passwordField.getText());
                } else {
                    newProps.setProperty(key, prop.getProperty(key));
                    if (!enumProps.hasMoreElements()) {
                        newProps.setProperty("pass",  passwordField.getText());
                    }
                }
            }
            
            
            
            key = "";
            if (!enumProps.hasMoreElements()) {
                newProps.setProperty("db", dbField.getText());
            }
            while (enumProps.hasMoreElements()) {
                key = (String) enumProps.nextElement();
                if (key.equals("db")) {
                    newProps.setProperty("db",  dbField.getText());
                } else {
                    newProps.setProperty(key, prop.getProperty(key));
                    if (!enumProps.hasMoreElements()) {
                        newProps.setProperty("db",  dbField.getText());
                    }
                }
            }
            
            
            os = new FileOutputStream(rutaPropertiesFile);
            newProps.store(os, "Properties File de SIAAT");
            os.close();
            JOptionPane.showMessageDialog(null, "Cambios guardados correctamente");
            this.dispose();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }                                                        

    /**
     * @param args the command line arguments
     */
    public void main(Usuarios user) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ConfigServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ConfigServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ConfigServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ConfigServer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        final Usuarios usuario = user;
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                frame = new ConfigServer(usuario);
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        frame.setVisible(false);
                        frame = null;
                    }
                });
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField dbField;
    private javax.swing.JLabel dbLabel;
    private javax.swing.JButton guardarButton;
    private javax.swing.JTextField hostField;
    private javax.swing.JLabel hostLabel;
    private javax.swing.JTextField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JTextField puertoField;
    private javax.swing.JLabel puertoLabel;
    private javax.swing.JTextField usuarioField;
    private javax.swing.JLabel usuarioLabel;
    // End of variables declaration//GEN-END:variables
}
